#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::string;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::istringstream;

struct Record
{
    Record(const string &word, int fre)
    : _word(word)
    , _frequency(fre)
    {

    }
	string _word;
	int _frequency;
};

class Dictionary
{
public:
    void read(const string &filename)
    {
        ifstream ifs(filename);
        if(!ifs)
        {
            cerr << "open file " << filename << " error!" << endl;
            return;
        }

        string line;
        while(getline(ifs, line))
        {
            istringstream iss(line);//内存字符串
            string word;
            while(iss >> word)//word是不是合格的单词,hello!
            {
                //如果单词不合理就需要进行处理
                string newWord = dealWord(word);
                //将处理好之后的单词newWord插入到vector
                insert(newWord);
            }
        }

        ifs.close();
    }

    void store(const string &filename)
    {
        ofstream ofs(filename);
        if(!ofs)
        {
            cerr << "open file " << filename << " error!" << endl;
            return;
        }

        //遍历vector，将数据写入到另外一个文件中
        for(size_t idx = 0; idx != _dict.size(); ++idx)
        {
            ofs << _dict[idx]._word 
                 << "  "  << _dict[idx]._frequency 
                 << endl;
        }

        ofs.close();

    }
    string dealWord(const string &word)
    {
        //hello! hell123
        for(size_t idx = 0; idx != word.size(); ++idx)
        {
            if(!isalpha(word[idx]))
            {
                return string();//非法单词就用空串进行处理
            }
        }

        return word;
    }

    void insert(const string &word)
    {
        //word有没有可能是空串
        if(word == string())
        {
            return;
        }

        //单词在vector是不是出现过,如果出现过就需要累加词频
        size_t idx = 0;
        for(; idx != _dict.size(); ++idx)
        {
            if(word == _dict[idx]._word)
            {
                ++_dict[idx]._frequency;
                break;
            }
        }

        if(idx == _dict.size())
        {
            _dict.push_back(Record(word, 1));
            /* _dict.push_back(word, 1);//error,语法报错 */
            /* _dict.push_back({word, 1});//ok, */
        }

    }
private:
	vector<Record> _dict;
};

int main()
{
    Dictionary dic;
    dic.read("The_Holy_Bible.txt");
    dic.store("wd.txt");//shift + *(高亮) n

    return 0;
}
